<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>至本电商 - 管理员后台</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
    <div class="admin-container">
        <!-- 左侧菜单 -->
        <div class="admin-sidebar">
            <div class="sidebar-header">
                <h2>管理员后台</h2>
            </div>
            <div class="sidebar-menu">
                <div class="menu-item active" data-view="chat">
                    <i class="fas fa-comments"></i>
                    <span>聊天</span>
                </div>
                <div class="menu-item" data-view="orders">
                    <i class="fas fa-shopping-cart"></i>
                    <span>订单管理</span>
                </div>
                <div class="menu-item" data-view="products">
                    <i class="fas fa-box"></i>
                    <span>产品管理</span>
                </div>
                <div class="menu-item" data-view="knowledge">
                    <i class="fas fa-book"></i>
                    <span>产品知识库</span>
                </div>
                <div class="menu-item" data-view="after-sales">
                    <i class="fas fa-tools"></i>
                    <span>售后处理</span>
                </div>
                <div class="menu-item" data-view="logout">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>退出登录</span>
                </div>
            </div>
        </div>

        <!-- 右侧内容 -->
        <div class="admin-content">
            <!-- 聊天区域 -->
            <div class="admin-chat-area">
                <!-- 聊天视图 - 现在包含用户列表 -->
                <div class="view" id="chat-view" style="display: flex;">
                    <!-- 用户列表 -->
                    <div class="user-list">
                        <div style="padding: 15px; border-bottom: 1px solid #e1e4e8;">
                            <h3>用户列表</h3>
                        </div>
                        <div id="pending-requests" style="padding: 10px; background-color: #fef3f2; color: #e74c3c; font-weight: 500; cursor: pointer;">
                            <!-- 待处理的人工请求会在这里显示 -->
                        </div>
                        <div id="request-details" style="display: none; padding: 10px; background-color: #f8f9fa; border-bottom: 1px solid #e1e4e8;">
                            <h4>待处理请求</h4>
                            <div id="request-list"></div>
                        </div>
                        <div id="user-items" style="max-height: 600px; overflow-y: auto;">
                            <!-- 用户列表会通过JavaScript动态加载 -->
                            <div class="loading-users">
                                <i class="fas fa-spinner fa-spin"></i>
                                <span>加载用户中...</span>
                            </div>
                        </div>
                    </div>

                    <!-- 聊天主区域 -->
                    <div style="flex: 1; display: flex; flex-direction: column;">
                        <div class="chat-header">
                            <h3>与 <span id="current-user">请选择用户</span> 聊天</h3>
                        </div>
                        <div class="chat-messages" id="admin-chat-messages">
                            <!-- 聊天消息会通过JavaScript动态加载 -->
                        </div>
                        <div class="chat-input-area">
                            <form id="admin-chat-form">
                                <input type="hidden" id="current-user-id">
                                <textarea class="chat-input" id="admin-message-input" placeholder="请输入回复..." required></textarea>
                                <button type="submit" class="send-btn">发送</button>
                            </form>
                        </div>
                    </div>
                </div>


                <!-- 订单管理视图 -->
                <div class="view" id="orders-view" style="display: none; overflow-y: auto;">
                    <div class="table-container">
                        <h2 style="margin-bottom: 20px;">订单管理</h2>
                        <table class="data-table">
                            <thead>
                            <tr>
                                <th>订单ID</th>
                                <th>用户ID</th>
                                <th>产品名称</th>
                                <th>数量</th>
                                <th>总金额</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="orders-table-body">
                            <!-- 订单数据会通过JavaScript动态加载 -->
                            <tr>
                                <td colspan="7" style="text-align: center;">加载订单中...</td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 产品管理视图 -->
                <div class="view" id="products-view" style="display: none; overflow-y: auto;">
                    <div style="padding: 20px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                            <h2>产品管理</h2>
                            <button id="add-product-btn" class="btn-primary">添加产品</button>
                        </div>

                        <div class="table-container">
                            <table class="data-table">
                                <thead>
                                <tr>
                                    <th>产品ID</th>
                                    <th>名称</th>
                                    <th>价格</th>
                                    <th>含量</th>
                                    <th>类别</th>
                                    <th>系列</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody id="products-table-body">
                                <!-- 产品数据会通过JavaScript动态加载 -->
                                <tr>
                                    <td colspan="7" style="text-align: center;">加载产品中...</td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- 产品知识库视图 -->
                <div class="view" id="knowledge-view" style="display: none; overflow-y: auto;">
                    <div style="padding: 20px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                            <h2>产品知识库</h2>
                            <button id="add-knowledge-btn" class="btn-primary">添加知识</button>
                        </div>

                        <div class="table-container">
                            <table class="data-table">
                                <thead>
                                <tr>
                                    <th>产品ID</th>
                                    <th>产品名称</th>
                                    <th>成分</th>
                                    <th>适用肤质</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody id="knowledge-table-body">
                                <!-- 动态加载内容 -->
                                </tbody>
                            </table>
                                    <!-- 产品知识数据会通过JavaScript动态加载 -->
                                    <tr>
                                        <td colspan="5" style="text-align: center;">加载产品知识中...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- 售后处理视图 -->
                <div class="view" id="after-sales-view" style="display: none; overflow-y: auto;">
                    <div style="padding: 20px;">
                        <h2 style="margin-bottom: 20px;">售后处理</h2>

                        <div class="table-container">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>订单ID</th>
                                        <th>用户ID</th>
                                        <th>产品名称</th>
                                        <th>状态</th>
                                        <th>申请时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="after-sales-table-body">
                                    <!-- 售后数据会通过JavaScript动态加载 -->
                                    <tr>
                                        <td colspan="6" style="text-align: center;">加载售后订单中...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 产品编辑模态框 -->
    <div id="product-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); justify-content: center; align-items: center;">
        <div style="background-color: white; padding: 20px; border-radius: 8px; width: 90%; max-width: 600px; max-height: 90vh; overflow-y: auto;">
            <h3 id="product-modal-title" style="margin-bottom: 15px;">添加产品</h3>
            <form id="product-form">
                <input type="hidden" id="product-id">
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px;">产品名称</label>
                    <input type="text" id="product-name" class="form-control" required>
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px;">价格</label>
                    <input type="number" id="product-price" class="form-control" step="0.01" min="0" required>
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px;">含量</label>
                    <input type="number" id="product-stock" class="form-control" min="0" required>
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px;">类别</label>
                    <input type="text" id="product-category" class="form-control" required>
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px;">系列</label>
                    <input type="text" id="product-series" class="form-control" required>
                </div>
                <div style="display: flex; justify-content: flex-end; gap: 10px;">
                    <button type="button" id="cancel-product" class="btn-secondary">取消</button>
                    <button type="submit" class="btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 产品知识编辑模态框 -->
    <div id="knowledge-modal">
        <div>
            <h3 id="knowledge-modal-title">添加产品知识</h3>
            <form id="knowledge-form">
                <input type="hidden" id="knowledge-product-id">
                <div>
                    <label>产品ID</label>
                    <input type="text" id="knowledge-product-id-input" required>
                </div>
                <div>
                    <label>成分</label>
                    <textarea id="knowledge-ingredients" required></textarea>
                </div>
                <div>
                    <label>功效</label>
                    <textarea id="knowledge-effect" required></textarea>
                </div>
                <div>
                    <label>适用肤质</label>
                    <input type="text" id="knowledge-skin-type" required>
                </div>
                <!-- 其他字段 -->
            </form>
        </div>
    </div>

    <script>
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 加载用户列表
            loadUserList();

            // 加载待处理的人工请求
            loadPendingChatRequests();

            // 添加 handleLogout 函数
            function handleLogout() {
                fetch('/logout')
                    .then(() => {
                        window.location.href = '/login';
                    })
                    .catch(error => {
                        console.error('退出登录错误:', error);
                        window.location.href = '/login';
                    });
            }

            // 菜单切换
            document.querySelectorAll('.menu-item').forEach(item => {
                item.addEventListener('click', function() {
                    const view = this.getAttribute('data-view'); // 获取 view 值

                    // 退出
                    if (view === 'logout') {
                        if (confirm('确定要退出登录吗？')) {
                            handleLogout();
                        }
                        return;
                    }
                    // 移除所有活动状态
                    document.querySelectorAll('.menu-item').forEach(menu => {
                        menu.classList.remove('active');
                    });
                    this.classList.add('active');

                    // 隐藏所有视图
                    document.querySelectorAll('.admin-chat-area .view').forEach(view => {
                        view.style.display = 'none';
                    });

                    // 显示对应的视图
                    const viewId = this.getAttribute('data-view') + '-view';
                    document.getElementById(viewId).style.display = viewId === 'chat-view' ? 'flex' : 'block';


                    // 特殊视图处理
                    if (viewId === 'orders-view') {
                        loadAllOrders();
                    } else if (viewId === 'products-view') {
                        loadAllProducts();
                    } else if (viewId === 'knowledge-view') {
                        loadAllProductKnowledge();
                    } else if (viewId === 'after-sales-view') {
                        loadAfterSalesOrders();
                    }
                });
            });

            // 管理员聊天表单提交
            document.getElementById('admin-chat-form').addEventListener('submit', async function(e) {
                e.preventDefault();

                const userId = document.getElementById('current-user-id').value;
                const messageInput = document.getElementById('admin-message-input');
                const message = messageInput.value.trim();

                if (userId && message) {
                    // 添加管理员消息到界面
                    addMessageToAdminChat(message, 'sent');

                    // 清空输入框
                    messageInput.value = '';

                    // 保存聊天记录（这里应该发送到服务器）
                    // 简化处理，实际项目中应该实现
                    console.log(`管理员发送给用户${userId}的消息:`, message);

                    // TODO: 发送消息到服务器保存
                }
            });

            // 产品管理相关
            document.getElementById('add-product-btn').addEventListener('click', function() {
                document.getElementById('product-modal-title').textContent = '添加产品';
                document.getElementById('product-form').reset();
                document.getElementById('product-id').value = '';
                document.getElementById('product-modal').style.display = 'flex';
            });

            document.getElementById('cancel-product').addEventListener('click', function() {
                document.getElementById('product-modal').style.display = 'none';
            });

            document.getElementById('product-form').addEventListener('submit', async function(e) {
                e.preventDefault();

                // 获取表单数据
                const productData = {
                    id: document.getElementById('product-id').value,
                    name: document.getElementById('product-name').value,
                    price: document.getElementById('product-price').value,
                    stock: document.getElementById('product-stock').value,
                    category: document.getElementById('product-category').value,
                    series: document.getElementById('product-series').value,
                    description: document.getElementById('product-description').value
                };

                // 保存产品（这里应该发送到服务器）
                try {
                    let success = false;
                    if (productData.id) {
                        // 更新产品
                        // TODO: 实现更新产品的API调用
                        success = true;
                    } else {
                        // 添加新产品
                        // TODO: 实现添加产品的API调用
                        success = true;
                    }

                    if (success) {
                        document.getElementById('product-modal').style.display = 'none';
                        loadAllProducts(); // 重新加载产品列表
                    } else {
                        alert('保存产品失败');
                    }
                } catch (error) {
                    console.error('保存产品错误:', error);
                    alert('保存产品失败');
                }
            });

            // 产品知识相关
            document.getElementById('add-knowledge-btn').addEventListener('click', function() {
                document.getElementById('knowledge-modal-title').textContent = '添加产品知识';
                document.getElementById('knowledge-form').reset();
                document.getElementById('knowledge-product-id').value = '';
                document.getElementById('knowledge-modal').style.display = 'flex';
            });

            document.getElementById('cancel-knowledge').addEventListener('click', function() {
                document.getElementById('knowledge-modal').style.display = 'none';
            });

            document.getElementById('knowledge-form').addEventListener('submit', async function(e) {
                e.preventDefault();

                // 获取表单数据
                const knowledgeData = {
                    product_id: document.getElementById('knowledge-product-id').value || document.getElementById('knowledge-product-id-input').value,
                    ingredients: document.getElementById('knowledge-ingredients').value,
                    usage_instructions: document.getElementById('knowledge-usage').value,
                    effect: document.getElementById('knowledge-effect').value,
                    skin_type: document.getElementById('knowledge-skin-type').value
                };

                // 保存产品知识（这里应该发送到服务器）
                try {
                    let success = false;
                    if (document.getElementById('knowledge-product-id').value) {
                        // 更新产品知识
                        // TODO: 实现更新产品知识的API调用
                        success = true;
                    } else {
                        // 添加新产品知识
                        // TODO: 实现添加产品知识的API调用
                        success = true;
                    }

                    if (success) {
                        document.getElementById('knowledge-modal').style.display = 'none';
                        loadAllProductKnowledge(); // 重新加载产品知识列表
                    } else {
                        alert('保存产品知识失败');
                    }
                } catch (error) {
                    console.error('保存产品知识错误:', error);
                    alert('保存产品知识失败');
                }
            });

            // 定时刷新
            setInterval(function() {
                loadPendingChatRequests();

                // 如果当前在聊天视图且有选中用户，刷新聊天记录
                if (document.getElementById('chat-view').style.display !== 'none' &&
                    document.getElementById('current-user-id').value) {
                    loadUserChatHistory(document.getElementById('current-user-id').value);
                }
            }, 5000);
        });

        // 加载用户列表
        async function loadUserList() {
            try {
                const response = await fetch('/api/admin/get_all_users');
                const data = await response.json();

                const userItems = document.getElementById('user-items');
                userItems.innerHTML = '';

                if (data.success && data.users.length > 0) {
                    data.users.forEach(user => {
                        const userItem = document.createElement('div');
                        userItem.className = 'user-item';
                        userItem.setAttribute('data-user-id', user.user_id);
                        userItem.setAttribute('data-username', user.username);
                        userItem.innerHTML = `
                    <div>${user.username}</div>
                    <div style="font-size: 12px; color: #7f8c8d;">用户ID: ${user.user_id}</div>
                `;

                        userItem.addEventListener('click', function() {
                            // 设置当前用户
                            const userId = this.getAttribute('data-user-id');
                            const username = this.getAttribute('data-username');
                            document.getElementById('current-user-id').value = userId;
                            document.getElementById('current-user').textContent = username;

                            // 加载聊天历史
                            loadUserChatHistory(userId);
                        });

                        userItems.appendChild(userItem);
                    });
                }
            } catch (error) {
                console.error('加载用户列表错误:', error);
            }
        }

        // 加载用户聊天历史
        async function loadUserChatHistory(userId) {
            try {
                // 获取该用户的所有聊天记录
                const response = await fetch(`/api/get_chat_history?user_id=${userId}`);
                const data = await response.json();

                const chatMessages = document.getElementById('admin-chat-messages');
                chatMessages.innerHTML = '';

                if (data.success && data.history.length > 0) {
                    // 按时间排序
                    const sortedHistory = [...data.history].sort((a, b) =>
                        new Date(a.created_at) - new Date(b.created_at)
                    );

                    // 显示所有消息
                    sortedHistory.forEach(item => {
                        if (item.sender_type === 'user') {
                            // 用户消息
                            addMessageToAdminChat(item.message, 'user', item.created_at);
                        } else if (item.sender_type === 'bot') {
                            // 机器人消息
                            addMessageToAdminChat(item.message, 'bot', item.created_at);
                        } else if (item.sender_type === 'admin') {
                            // 管理员消息
                            addMessageToAdminChat(item.message, 'admin', item.created_at);
                        }
                    });
                }
            } catch (error) {
                console.error('加载聊天历史错误:', error);
            }
        }

        // 添加消息到管理员聊天界面
        function addMessageToAdminChat(message, sender, timestamp) {
            const chatMessages = document.getElementById('admin-chat-messages');

            const messageDiv = document.createElement('div');

            // 根据发送者设置样式
            if (sender === 'admin') {
                messageDiv.className = 'message sent';  // 管理员消息
            } else if (sender === 'bot') {
                messageDiv.className = 'message received';  // 机器人消息
            } else {
                messageDiv.className = 'message received';  // 用户消息
            }

            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = message;

            const timeDiv = document.createElement('div');
            timeDiv.className = 'message-time';

            // 设置时间和发送者
            const date = timestamp ? new Date(timestamp) : new Date();
            const timeString = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;

            if (sender === 'admin') {
                timeDiv.textContent = `我（管理员） ${timeString}`;
            } else if (sender === 'bot') {
                timeDiv.textContent = `客服机器人 ${timeString}`;
            } else {
                timeDiv.textContent = `用户 ${timeString}`;
            }

            messageDiv.appendChild(contentDiv);
            messageDiv.appendChild(timeDiv);
            chatMessages.appendChild(messageDiv);

            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 加载待处理的人工请求
        async function loadPendingChatRequests() {
            try {
                const response = await fetch('/api/admin/get_pending_chat_requests');
                const data = await response.json();

                const pendingRequests = document.getElementById('pending-requests');

                if (data.success && data.requests.length > 0) {
                    pendingRequests.innerHTML = `<i class="fas fa-bell"></i> 有 ${data.requests.length} 个未处理的人工请求`;

                    // 添加点击事件，显示详细请求
                    pendingRequests.onclick = function() {
                        let requestsHtml = '<div style="padding: 10px; background-color: #fef3f2;">';
                        data.requests.forEach(request => {
                            requestsHtml += `
                                <div style="padding: 10px; margin-bottom: 10px; background-color: white; border-radius: 4px;">
                                    <div>用户ID: ${request.user_id}</div>
                                    <div style="font-size: 12px; color: #7f8c8d;">请求时间: ${formatDate(request.created_at)}</div>
                                    <button class="accept-request btn-primary" style="margin-top: 10px; padding: 5px 10px; font-size: 14px;"
                                            data-request-id="${request.request_id}"
                                            data-user-id="${request.user_id}">
                                        接受请求
                                    </button>
                                </div>
                            `;
                        });
                        requestsHtml += '</div>';

                        pendingRequests.innerHTML = requestsHtml;

                        // 绑定接受请求按钮事件
                        document.querySelectorAll('.accept-request').forEach(button => {
                            button.addEventListener('click', async function() {
                                const requestId = this.getAttribute('data-request-id');
                                const userId = this.getAttribute('data-user-id');

                                try {
                                    const response = await fetch(`/api/admin/accept_chat_request/${requestId}`);
                                    const data = await response.json();

                                    if (data.success) {
                                        // 切换到聊天视图并选中该用户
                                        document.querySelector('.menu-item[data-view="chat"]').click();

                                        // 选中用户
                                        document.querySelectorAll('.user-item').forEach(item => {
                                            if (item.getAttribute('data-user-id') === userId) {
                                                item.click();
                                            }
                                        });

                                        // 刷新请求列表
                                        loadPendingChatRequests();
                                    } else {
                                        alert('接受请求失败');
                                    }
                                } catch (error) {
                                    console.error('接受请求错误:', error);
                                    alert('接受请求失败');
                                }
                            });
                        });
                    };
                } else {
                    pendingRequests.innerHTML = '';
                    pendingRequests.onclick = null;
                }
            } catch (error) {
                console.error('加载待处理请求错误:', error);
            }
        }







        // 加载所有订单
        async function loadAllOrders() {
            try {
                const response = await fetch('/api/admin/get_all_orders');
                const data = await response.json();

                const tableBody = document.getElementById('orders-table-body');

                if (data.success) {
                    if (data.orders.length > 0) {
                        tableBody.innerHTML = '';

                        data.orders.forEach(order => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                        <td>${order.order_id}</td>
                        <td>${order.user_id}</td>
                        <td>${order.product_name}</td>
                        <td>${order.quantity}</td>
                        <td>¥${order.total_amount}</td>
                        <td><span class="order-status">${order.display_status}</span></td>
                        <td class="table-actions">
                            ${order.after_sales_status === 'applied' ?
                                `<button class="action-btn approve-btn" data-order-id="${order.order_id}">同意</button>
                                 <button class="action-btn reject-btn" data-order-id="${order.order_id}">拒绝</button>` :
                                order.display_status === '售后中' ?
                                    '<span>处理中</span>' :
                                    '-'}
                        </td>
                    `;

                            tableBody.appendChild(row);
                        });

                        // 绑定同意按钮事件
                        document.querySelectorAll('.approve-btn').forEach(button => {
                            button.addEventListener('click', function() {
                                const orderId = this.getAttribute('data-order-id');
                                processAfterSales(orderId, 'approve');
                            });
                        });

                        // 绑定拒绝按钮事件
                        document.querySelectorAll('.reject-btn').forEach(button => {
                            button.addEventListener('click', function() {
                                const orderId = this.getAttribute('data-order-id');
                                processAfterSales(orderId, 'reject');
                            });
                        });
                    } else {
                        tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center;">暂无订单记录</td></tr>';
                    }
                } else {
                    tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #e74c3c;">加载订单失败</td></tr>';
                }
            } catch (error) {
                console.error('加载订单错误:', error);
                document.getElementById('orders-table-body').innerHTML = '<tr><td colspan="7" style="text-align: center; color: #e74c3c;">加载订单失败</td></tr>';
            }
        }

        // 新增函数：处理售后申请
        async function processAfterSales(orderId, action) {
            if (!confirm(`确定要${action === 'approve' ? '同意' : '拒绝'}该售后申请吗？`)) {
                return;
            }

            try {
                const response = await fetch('/api/process_after_sales', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        order_id: orderId,
                        action: action
                    })
                });

                const data = await response.json();

                if (data.success) {
                    alert(data.message);
                    loadAllOrders(); // 重新加载订单
                } else {
                    alert(data.message);
                }
            } catch (error) {
                console.error('处理售后申请错误:', error);
                alert('处理售后申请失败');
            }
        }

        // 加载所有产品
        async function loadAllProducts() {
            try {
                // 调用API获取产品数据
                const response = await fetch('/api/admin/products');

                // 检查响应状态
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                // 解析JSON数据
                const data = await response.json();

                const tableBody = document.getElementById('products-table-body');
                tableBody.innerHTML = '';

                // 检查是否成功获取数据
                if (data.success && data.products && data.products.length > 0) {
                    // 使用真实数据填充表格
                    data.products.forEach(product => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                    <td>${product.product_id}</td>
                    <td>${product.name}</td>
                    <td>¥${product.price}</td>
                    <td>${product.stock}</td>
                    <td>${product.category}</td>
                    <td>${product.series}</td>
                    <td class="table-actions">
                        <button class="action-btn edit-btn edit-product" data-product-id="${product.product_id}">编辑</button>
                        <button class="action-btn delete-btn delete-product" data-product-id="${product.product_id}">删除</button>
                    </td>
                `;
                        tableBody.appendChild(row);
                    });

                    // 绑定编辑和删除按钮事件
                    document.querySelectorAll('.edit-product').forEach(button => {
                        button.addEventListener('click', async function() {
                            const productId = this.getAttribute('data-product-id');

                            try {
                                // 调用API获取产品详情
                                const response = await fetch(`/api/admin/products/${productId}`);

                                if (!response.ok) {
                                    throw new Error(`HTTP error! status: ${response.status}`);
                                }

                                const productData = await response.json();

                                if (productData.success && productData.product) {
                                    // 填充编辑表单
                                    document.getElementById('product-modal-title').textContent = '编辑产品';
                                    document.getElementById('product-id').value = productData.product.product_id;
                                    document.getElementById('product-name').value = productData.product.name;
                                    document.getElementById('product-price').value = productData.product.price;
                                    document.getElementById('product-stock').value = productData.product.stock;
                                    document.getElementById('product-category').value = productData.product.category;
                                    document.getElementById('product-series').value = productData.product.series;
                                    document.getElementById('product-modal').style.display = 'flex';
                                } else {
                                    alert('获取产品详情失败: ' + (productData.message || '未知错误'));
                                }
                            } catch (error) {
                                console.error('加载产品详情失败:', error);
                                alert('加载产品详情失败: ' + error.message);
                            }
                        });
                    });

                    document.querySelectorAll('.delete-product').forEach(button => {
                        button.addEventListener('click', async function() {
                            const productId = this.getAttribute('data-product-id');

                            if (confirm('确定要删除这个产品吗？')) {
                                try {
                                    // 调用API删除产品
                                    const response = await fetch(`/api/admin/products/${productId}`, {
                                        method: 'DELETE'
                                    });

                                    const result = await response.json();

                                    if (result.success) {
                                        alert('产品删除成功');
                                        loadAllProducts(); // 重新加载产品列表
                                    } else {
                                        alert('删除产品失败: ' + result.message);
                                    }
                                } catch (error) {
                                    console.error('删除产品失败:', error);
                                    alert('删除产品失败: ' + error.message);
                                }
                            }
                        });
                    });
                } else {
                    // 没有产品数据时显示提示
                    tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center;">暂无产品记录</td></tr>';
                }
            } catch (error) {
                console.error('加载产品错误:', error);
                document.getElementById('products-table-body').innerHTML = `
            <tr>
                <td colspan="7" style="text-align: center; color: #e74c3c;">
                    加载产品失败: ${error.message}
                </td>
            </tr>
        `;
            }
        }

        // 加载所有产品知识
        // 完善loadAllProductKnowledge函数，添加加载状态、错误提示和空数据处理
        async function loadAllProductKnowledge() {
            // 获取DOM元素
            const tableBody = document.getElementById('knowledge-table-body');
            const loadingIndicator = document.getElementById('loading-indicator');
            const errorMessage = document.getElementById('error-message');
            const editModal = document.getElementById('edit-modal');

            // 重置状态
            tableBody.innerHTML = '';
            showElement(loadingIndicator);
            hideElement(errorMessage);

            try {
                // 发起API请求
                const response = await fetch('/api/admin/product-knowledge');

                // 检查HTTP响应状态
                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
                }

                const data = await response.json();

                // 隐藏加载指示器
                hideElement(loadingIndicator);

                // 处理API响应
                if (data.success) {
                    if (data.knowledge && data.knowledge.length > 0) {
                        // 渲染数据表格
                        data.knowledge.forEach(item => {
                            const row = document.createElement('tr');
                            row.dataset.productId = item.product_id;
                            row.innerHTML = `
                        <td>${escapeHtml(item.product_id)}</td>
                        <td>${escapeHtml(item.name || '未知产品')}</td>
                        <td>${escapeHtml(item.ingredients || '未提供')}</td>
                        <td>${escapeHtml(item.skin_type || '未指定')}</td>
                        <td>
                            <button class="edit-knowledge bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded"
                                    data-product-id="${escapeHtml(item.product_id)}">编辑</button>
                            <button class="delete-knowledge bg-red-500 hover:bg-red-600 text-white px-3 py-1 rounded ml-2"
                                    data-product-id="${escapeHtml(item.product_id)}">删除</button>
                        </td>
                    `;
                            tableBody.appendChild(row);
                        });

                        // 绑定按钮事件 - 在内部定义编辑和删除逻辑
                        document.querySelectorAll('.edit-knowledge').forEach(button => {
                            button.addEventListener('click', async function() {
                                const productId = this.dataset.productId;
                                try {
                                    // 显示加载状态
                                    showElement(document.getElementById('modal-loading'));

                                    // 获取产品知识详情
                                    const response = await fetch(`/api/admin/product-knowledge?product_id=${encodeURIComponent(productId)}`);
                                    if (!response.ok) {
                                        throw new Error(`获取产品知识失败: ${response.statusText}`);
                                    }

                                    const data = await response.json();
                                    if (!data.success || !data.knowledge) {
                                        throw new Error(data.message || '未找到产品知识数据');
                                    }

                                    const knowledge = data.knowledge;

                                    // 填充表单数据
                                    document.getElementById('edit-product-id').value = knowledge.product_id;
                                    document.getElementById('edit-product-name').value = knowledge.name || '';
                                    document.getElementById('edit-ingredients').value = knowledge.ingredients || '';
                                    document.getElementById('edit-skin-type').value = knowledge.skin_type || '';

                                    // 显示编辑弹窗
                                    hideElement(document.getElementById('modal-loading'));
                                    showElement(editModal);

                                } catch (error) {
                                    console.error('编辑产品知识失败:', error);
                                    hideElement(document.getElementById('modal-loading'));
                                    alert(`加载编辑数据失败: ${error.message}`);
                                }
                            });
                        });

                        document.querySelectorAll('.delete-knowledge').forEach(button => {
                            button.addEventListener('click', async function() {
                                const productId = this.dataset.productId;
                                if (!confirm(`确定要删除产品ID为 ${productId} 的知识数据吗？此操作不可恢复！`)) {
                                    return;
                                }

                                try {
                                    // 显示加载状态
                                    const row = document.querySelector(`tr[data-product-id="${escapeHtml(productId)}"]`);
                                    if (row) row.classList.add('opacity-50');

                                    // 调用删除API
                                    const response = await fetch(`/api/admin/product-knowledge?product_id=${encodeURIComponent(productId)}`, {
                                        method: 'DELETE',
                                        headers: { 'Content-Type': 'application/json' }
                                    });

                                    const data = await response.json();

                                    if (!response.ok || !data.success) {
                                        throw new Error(data.message || `删除失败: ${response.statusText}`);
                                    }

                                    // 删除成功，刷新列表
                                    alert('产品知识已成功删除');
                                    loadAllProductKnowledge();

                                } catch (error) {
                                    console.error('删除产品知识失败:', error);
                                    alert(`删除失败: ${error.message}`);
                                    // 恢复行样式
                                    const row = document.querySelector(`tr[data-product-id="${escapeHtml(productId)}"]`);
                                    if (row) row.classList.remove('opacity-50');
                                }
                            });
                        });

                        // 保存编辑的事件处理
                        document.getElementById('edit-form').addEventListener('submit', async function(e) {
                            e.preventDefault();

                            const productId = document.getElementById('edit-product-id').value;
                            const updatedData = {
                                product_id: productId,
                                ingredients: document.getElementById('edit-ingredients').value,
                                skin_type: document.getElementById('edit-skin-type').value
                            };

                            try {
                                showElement(document.getElementById('save-loading'));
                                disableFormButtons(true);

                                const response = await fetch('/api/admin/product-knowledge', {
                                    method: 'PUT',
                                    headers: { 'Content-Type': 'application/json' },
                                    body: JSON.stringify(updatedData)
                                });

                                const data = await response.json();

                                if (!response.ok || !data.success) {
                                    throw new Error(data.message || `保存失败: ${response.statusText}`);
                                }

                                // 保存成功
                                hideElement(editModal);
                                alert('产品知识已成功更新');
                                loadAllProductKnowledge();

                            } catch (error) {
                                console.error('保存产品知识失败:', error);
                                alert(`保存失败: ${error.message}`);
                            } finally {
                                hideElement(document.getElementById('save-loading'));
                                disableFormButtons(false);
                            }
                        });
                    } else {
                        // 处理空数据情况
                        tableBody.innerHTML = `
                    <tr>
                        <td colspan="5" class="text-center py-4 text-gray-500">
                            <i class="fas fa-info-circle mr-2"></i>暂无产品知识数据，请添加
                        </td>
                    </tr>
                `;
                    }
                } else {
                    throw new Error(data.message || '加载产品知识失败');
                }
            } catch (error) {
                console.error('加载产品知识失败:', error);
                hideElement(loadingIndicator);
                errorMessage.textContent = `加载失败: ${error.message}，请重试`;
                showElement(errorMessage);

                tableBody.innerHTML = `
            <tr>
                <td colspan="5" class="text-center py-4">
                    <button id="retry-load" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded">
                        <i class="fas fa-sync-alt mr-1"></i>重试
                    </button>
                </td>
            </tr>
        `;

                document.getElementById('retry-load').addEventListener('click', loadAllProductKnowledge);
            }
        }

        // 辅助函数
        function showElement(element) {
            if (element) element.classList.remove('hidden');
        }

        function hideElement(element) {
            if (element) element.classList.add('hidden');
        }

        function escapeHtml(unsafe) {
            if (!unsafe) return '';
            return unsafe.toString()
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        function disableFormButtons(disable) {
            const buttons = document.querySelectorAll('#edit-form button');
            buttons.forEach(button => button.disabled = disable);
        }

        // 页面加载完成后自动加载数据
        document.addEventListener('DOMContentLoaded', loadAllProductKnowledge);



        // 加载售后订单
        async function loadAfterSalesOrders() {
            try {
                // TODO: 实现加载售后订单的API调用
                // 模拟数据
                const afterSalesOrders = [
                    {
                        order_id: 1001,
                        user_id: 1,
                        product_name: '保湿面霜',
                        status: '售后中',
                        created_at: new Date().toISOString()
                    },
                    {
                        order_id: 1005,
                        user_id: 3,
                        product_name: '精华液',
                        status: '售后中',
                        created_at: new Date().toISOString()
                    }
                ];

                const tableBody = document.getElementById('after-sales-table-body');
                tableBody.innerHTML = '';

                afterSalesOrders.forEach(order => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${order.order_id}</td>
                        <td>${order.user_id}</td>
                        <td>${order.product_name}</td>
                        <td><span class="order-status status-after-sales">${order.status}</span></td>
                        <td>${formatDate(order.created_at)}</td>
                        <td class="table-actions">
                            <button class="action-btn edit-btn process-after-sales" data-order-id="${order.order_id}">处理</button>
                        </td>
                    `;

                    tableBody.appendChild(row);
                });

                // 绑定处理按钮事件
                document.querySelectorAll('.process-after-sales').forEach(button => {
                    button.addEventListener('click', async function() {
                        const orderId = this.getAttribute('data-order-id');
                        // TODO: 实现处理售后订单的功能
                        if (confirm(`确定要完成订单 ${orderId} 的售后处理吗？`)) {
                            alert(`订单 ${orderId} 的售后已完成`);
                            loadAfterSalesOrders();
                        }
                    });
                });
            } catch (error) {
                console.error('加载售后订单错误:', error);
                document.getElementById('after-sales-table-body').innerHTML = '<tr><td colspan="6" style="text-align: center; color: #e74c3c;">加载售后订单失败</td></tr>';
            }
        }

        // 格式化日期
        function formatDate(dateString) {
            const date = new Date(dateString);
            return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
        }
    </script>
</body>
</html>